#!/bin/bash

export LANG=zh_CN.UTF-8

export LC_ALL=zh_CN.UTF-8

#FRPS_HOME is the location of the bin files of frps
export FRPS_HOME={{home}}/{{service_name}}

#FRPS_USAGE is the message if this script is called without any options
FRPS_USAGE="Usage: $0 {\e[00;32mstart\e[00m|\e[00;31mstop\e[00m|\e[00;32mstatus\e[00m|\e[00;31mrestart\e[00m}"

#SHUTDOWN_WAIT is wait time in seconds for java proccess to stop
SHUTDOWN_WAIT=20

frps_pid() {
        echo `ps -fe | grep $FRPS_HOME | grep -v grep | tr -s " "|cut -d" " -f2`
}

start() {
  pid=$(frps_pid)
  if [ -n "$pid" ]
  then
    echo -e "\e[00;31mFrps is already running (pid: $pid)\e[00m"
  else
    # Start frps
    echo -e "\e[00;32mStarting frps\e[00m"
    ./$FRPS_HOME -c {{config_file_path}}/frps.ini &
    status
  fi
  return 0
}

status(){
          pid=$(frps_pid)
          if [ -n "$pid" ]; then echo -e "\e[00;32mFrps is running with pid: $pid\e[00m"
          else echo -e "\e[00;31mFrps is not running\e[00m"
          fi
}

terminate() {
  echo -e "\e[00;31mTerminating Frps\e[00m"
  kill -9 $(frps_pid)
}

stop() {
  pid=$(frps_pid)
  if [ -n "$pid" ]
  then
    echo -e "\e[00;31mStoping Frps\e[00m"
    terminate
  else
    echo -e "\e[00;31mFrps is not running\e[00m"
  fi

  return 0
}

case $1 in

        start)
          start
        ;;

        stop)
          stop
        ;;

        restart)
          stop
          start
        ;;

        status)
                status

        ;;

        *)
                echo -e $FRPS_USAGE
        ;;
esac
exit 0
